<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>indexDB</title>
    <script src="./main.js"></script>
  </head>
  <body>
    <script>
      /**
       * 打开数据库
       * @param {object} dbName 数据库的名字
       * @param {string} storeName 仓库名称
       * @param {string} version 数据库的版本
       * @return {object} 该函数会返回一个数据库实例
       */
      function openDB(dbName, version, data) {
        return new Promise((resolve, reject) => {
          //  兼容浏览器
          var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

          let db;

          // IDBOpenDBRequest 请求对象，打开数据库，若没有则会创建
          const request = indexedDB.open(dbName, version);

          // 数据库打开成功回调
          request.onsuccess = function (event) {
            db = event.target.result; // 数据库对象 IDBDatabase
            console.log('数据库打开成功');

            resolve(db);
          };

          // 数据库打开失败的回调
          request.onerror = function (event) {
            console.log('数据库打开报错');
          };

          // 数据库有更新时候的回调
          request.onupgradeneeded = function (event) {
            console.log('更新数据库');
            // 数据库创建或升级的时候会触发
            console.log('onupgradeneeded');

            db = event.target.result; // 数据库对象

            var objectStore;

            // 创建存储库
            objectStore = db.createObjectStore('signalChat', {
              keyPath: 'sequenceId' // 这是主键
              // autoIncrement: true // 实现自增
            });

            // 创建索引，在后面查询数据的时候可以根据索引查
            objectStore.createIndex('link', 'link', { unique: false });
            objectStore.createIndex('sequenceId', 'sequenceId', { unique: false });
            objectStore.createIndex('messageType', 'messageType', {
              unique: false
            });
          };
        });
      }

      /**
       * 新增数据
       * @param {object} db 数据库实例
       * @param {string} storeName 仓库名称
       * @param {string} data 数据
       */
      function addData(db, storeName, data) {
        var request = db
          .transaction(storeName, 'readwrite') // 事务对象 指定表格名称和操作模式（"只读"或"读写"）
          .objectStore('signalChat') // 仓库对象
          .add(data);

        request.onsuccess = function (event) {
          console.log('数据写入成功');
        };

        request.onerror = function (event) {
          console.log('数据写入失败');
        };
      }

      /**
       * 通过主键读取数据
       * @param {object} db 数据库实例
       * @param {string} storeName 仓库名称
       * @param {string} key 主键值
       */
      function getDataByKey(db, storeName, key) {
        return new Promise((resolve, reject) => {
          var transaction = db.transaction([storeName]); // 事务
          var objectStore = transaction.objectStore(storeName); // 仓库对象
          var request = objectStore.get(key); // 通过主键获取数据

          request.onerror = function (event) {
            console.log('事务失败');
          };

          request.onsuccess = function (event) {
            console.log('主键查询结果: ', request.result);
            resolve(request.result);
          };
        });
      }
    </script>
    
    <input id="dbName" type="text" value="basep" />
    <button onclick="createDB()" type="button">点击创建数据库</button>
    <script>
      let dbs = undefined;
      function createDB() {
        const data = document.getElementById('data').value;
        const datas = { link: data, sequenceId: data, messageType: data };
        const dbName = document.getElementById('dbName').value;
        openDB(dbName, 4, datas).then(DB => {
          console.log('IDBDatabase:', DB);
          dbs = DB;
        });
      }
    </script>

    <hr />
    <input id="data" type="text" value="数据" />
    <button onclick="add()" type="button">点击添加数据</button>
    <script>
      function add() {
        const data = document.getElementById('data').value;
        console.log({ dbs });
        addData(dbs, 'signalChat', { link: data, sequenceId: data, messageType: data });
      }
    </script>
  </body>
</html>
